from sys import stdout
from logging import *
from .color import *

'''
    A tricky modification for `logging.StreamHandler`

    see `color.py` for some information about
      platform support. 
'''

# new log level
NOTIFY = INFO + 1

level_to_decos = {
    CRITICAL    : deco('', FG_RED, bold=True),
    ERROR       : deco('', FG_RED),
    WARNING     : deco('', FG_YELLOW, bold=True),
    INFO        : deco('', FG_WHITE),
    DEBUG       : deco('', FG_GREEN),
    NOTSET      : deco('', FG_WHITE),  # same as INFO
}

class ConsoleHandler(StreamHandler):

    def __init__(self, stream=stdout):
        super().__init__(stream)
        self.addLogLevel(NOTIFY, 'NOTIFY', deco('', FG_YELLOW))

    def addLogLevel(self, level, levelName, deco_str=deco('', FG_WHITE)):
        try:
            level_to_decos[level] = deco_str
        finally:
            pass
        addLevelName(level, levelName)

    def emit(self, record):
        const_deco = level_to_decos.get(record.levelno, level_to_decos[NOTSET])
        # record.message is dynamically generated by record.getMessage().
        record.msg = deco(record.msg, const_deco=const_deco) + reset()
        # all properties of `record` that are of string type can be decorated.
        record.levelname = deco(record.levelname, bold=True) + reset()
        record.filename = deco(record.filename, FG_MAGENTA) + reset()
        return super().emit(record)

    # def format(self, record):
    #     ''' NOT COMPATIBLE with `emit()`, don not use them together. '''
    #     msg = super().format(record)
    #     const_deco = level_to_decos.get(record.levelno, NOTSET)
    #     return deco(msg, const_deco=const_deco) + reset()
